package czx.wt.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wangfan.endecrypt.utils.EndecryptUtils;
import czx.wt.common.exception.BusinessException;
import czx.wt.common.response.ComResponseEnum;
import czx.wt.common.response.ResponseData;
import czx.wt.system.pojo.User;
import czx.wt.system.pojo.UserRole;
import czx.wt.system.service.IUserRoleService;
import czx.wt.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.RequiresPermissions;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ChenZhiXiang
 * @Date: 2019/6/25 22:18
 * @Description: 用户控制层
 */
@Api(value = "用户相关接口",tags = "用户相关接口")
@RestController
@RequestMapping("${api.version}")
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @ApiOperation(value = "查询所有用户",notes = "根据一些条件查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "第几页", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "searchKey", value = "筛选条件字段",required = false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "searchValue", value = "筛选条件关键字", required = false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @RequiresPermissions("get:/v1/findAllUser")
    @GetMapping("/findAllUser")
    public Object findAllUser(@RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize,
                       @RequestParam(value = "searchKey",required = false) String searchKey,
                       @RequestParam(value = "searchValue",required = false) String searchValue,
                       @RequestParam(value = "access_token",required = true) String access_token) throws Exception {

        return userService.getAllUser(pageNum,pageSize);
    }

    @ApiOperation(value = "增加用户",notes = "增加用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "user", paramType = "body"),
            @ApiImplicitParam(name = "roleIds", value = "角色编码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @RequiresPermissions("post:/v1/addUser")
    @PostMapping("/addUser")
    public Object addUser(@Valid @RequestBody User user,
                          @RequestParam(value = "roleIds",required = false) String roleIds,
                          @RequestParam(value = "access_token",required = true) String access_token) throws Exception {
        // 角色的编码的数组
        String[] split = roleIds.split(",");
        // 是否添加成功
        user.setPassword(EndecryptUtils.encrytMd5(user.getPassword(),user.getUsername(),3));
        boolean isAddSuccess = userService.insert(user);
        if (isAddSuccess){
            List<UserRole> list = new ArrayList<>();
            for (int i = 0;i < split.length;i++){
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(Integer.valueOf(split[i]));
                list.add(userRole);
            }
            if (!userRoleService.insertBatch(list)){
                throw new BusinessException(ComResponseEnum.USER5);
            }
            return ResponseData.SUCCESS;
        }
        return ResponseData.OPERATION;
    }

    @ApiOperation(value = "修改用户",notes = "修改用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "user", paramType = "body"),
            @ApiImplicitParam(name = "roleIds", value = "角色编码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @RequiresPermissions("post:/v1/updateUser")
    @PostMapping("/updateUser")
    public Object updateUser(@Valid @RequestBody User user,
                          @RequestParam(value = "roleIds",required = false) String roleIds,
                          @RequestParam(value = "access_token",required = true) String access_token) throws Exception {
        // 截取角色编码
        String[] split = roleIds.split(",");
        boolean isSuccessUpdate = userService.updateById(user);
        // 是否更新成功
        if (isSuccessUpdate){
            // 如果用户已经更新成功，那就继续更新用户与角色的关系
            // 删除原有的
            boolean isDelSuccess = userRoleService.delete(new EntityWrapper<UserRole>().eq("user_id",user.getUserId()));
            // 删除成功
            if (isDelSuccess){
                List<UserRole> list = new ArrayList<>();
                for (String roleId : split){
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(Integer.valueOf(roleId));
                    list.add(userRole);
                }
                //批量插入是否成功
                boolean isAddSuccess = userRoleService.insertBatch(list);
                if (isAddSuccess){
                    return ResponseData.SUCCESS;
                } else {
                    // 不成功就抛异常，便于回滚所有操作
                    throw new BusinessException(ComResponseEnum.OPERATION);
                }
            } else {
                // 不成功就抛异常，便于回滚所有操作
                throw new BusinessException(ComResponseEnum.OPERATION);
            }
        }
        return ResponseData.OPERATION;
    }

    @RequiresPermissions("delete:/v1/delUserById")
    @ApiOperation(value = "删除用户", notes = "根据用户编码删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "form")
    })
    @DeleteMapping("/delUserById")
    public Object delUserById(@RequestParam(value = "userId",required = true) Integer userId) {
        if (userService.deleteById(userId)) {
            return ResponseData.SUCCESS;
        }
        return ResponseData.OPERATION;
    }
}
